import axios from 'axios'

const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://113.45.152.122:3001/api',
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器添加token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    console.log('请求拦截器 - 当前token:', token)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('请求拦截器 - 已添加Authorization头')
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器处理错误
apiClient.interceptors.response.use(
  response => response.data,
  error => {
    // 处理401错误，清除token并重定向到登录页
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/auth/login'
    }
    return Promise.reject(error)
  }
)

export default apiClient